<template>
    <div id="friend-merchant-manage" class="w-h-100 pos-r flex-1 apply-container page-public-s" style="box-sizing: border-box;overflow:hidden;">
        <div class="w-h-100 ver-flex pos-a" style="box-sizing: border-box; padding: 6px;">
            <div v-if="$hasPer('QuestionBank:add') || $hasPer('QuestionBank:batchUpload') || $hasPer('QuestionBank:batchDown') || $hasPer('QuestionBank:excel')" style="box-sizing: border-box;">
                <el-card shadow="never" :body-style="{ paddingBottom: '0' }">
                    <el-form class="box-f" ref="queryForm" :inline="true">
                        <el-form-item >
                            <el-button v-if="$hasPer('QuestionBank:add')" @click="nodeClick('','add')" icon="ele-Plus" type="primary"> 新增 </el-button>
                            <el-button v-if="$hasPer('QuestionBank:batchUpload')" @click="funClick(0)" icon="ele-Upload"> 批量上传 </el-button>
                            <el-button v-if="$hasPer('QuestionBank:batchDown')" @click="funClick(1)" icon="ele-Download"> 模板下载 </el-button>
                            <el-button v-if="$hasPer('QuestionBank:excel')" @click="handleExport" icon="ele-Download"> 导出数据 </el-button>
                        </el-form-item>
                    </el-form>
                </el-card>
            </div>

            <div style="box-sizing: border-box;" class="flex-1 pos-r">
                <div class="pos-a w-h-100" style="box-sizing: border-box;">
                    <el-card class="box-card w-h-100" shadow="never" style="margin-top: 16px;">
                        <div style="" class="w-h-100 ver-flex">
                            <div class="flex-1 pos-r">
                                <div class="pos-a w-h-100">
                                    <el-table ref="excelRef" :data="list" class="w-h-100" style="width: 100%" border v-loading="loading" element-loading-background="rgba(0, 0, 0, 0.5)">
                                        <!-- <el-table-column type="index" label="序号" width="55" :show-overflow-tooltip="true" align="center" :index="indexMethod" /> -->
                                        <el-table-column min-width="200" :show-overflow-tooltip="true" label="培训计划名称"  align="center">
                                            <el-table-column :show-overflow-tooltip="true" min-width="200" align="center">
                                                <template #header>
                                                    <SearchModel typeId="s_Plan" typeVal="select" @searchHandel="searchHandel" :basicsInfo="basicsInfo" />
                                                </template>
                                                <template #default="scope">
                                                    <span v-if="scope.row.v_TrainingPlanName">{{ scope.row.v_TrainingPlanName }}</span>
                                                    <span v-else> - </span>
                                                </template>
                                            </el-table-column>
                                        </el-table-column>

                                        <el-table-column min-width="200" :show-overflow-tooltip="true" label="考题类型"  align="center">
                                            <el-table-column :show-overflow-tooltip="true" min-width="200" align="center">
                                                <template #header>
                                                    <SearchModel typeId="s_Type" typeVal="select" @searchHandel="searchHandel" :basicsInfo="basicsInfo" />
                                                </template>
                                                <template #default="scope">
                                                    <span v-if="scope.row.n_Type === 0" style="color: #409EFF;">{{scope.row.v_TypeName}}</span>
                                                    <span v-if="scope.row.n_Type === 1" style="color: #67C23A;">{{scope.row.v_TypeName}}</span>
                                                    <span v-if="scope.row.n_Type === 2" style="color: #E6A23C;">{{scope.row.v_TypeName}}</span>
                                                </template>
                                            </el-table-column>
                                        </el-table-column>
                                        <el-table-column min-width="200" label="单题分数"  align="center" prop="n_Score" sortable>
                                            <el-table-column :show-overflow-tooltip="true" min-width="200" align="center">
                                                <template #header>
                                                    <SearchModel typeId="i_Score" typeVal="input" @searchHandel="searchHandel" :basicsInfo="basicsInfo" />
                                                </template>
                                                <template #default="scope">
                                                    <span>{{ scope.row.n_Score }}</span>
                                                </template>
                                            </el-table-column>
                                        </el-table-column>

                                        <el-table-column min-width="200" :show-overflow-tooltip="true" label="排序号"  align="center" prop="n_Sort" sortable>
                                            <el-table-column :show-overflow-tooltip="true" min-width="200" align="center">
                                                <template #header>
                                                    <SearchModel typeId="i_Sort" typeVal="input" @searchHandel="searchHandel" :basicsInfo="basicsInfo" />
                                                </template>
                                                <template #default="scope">
                                                    <span>{{ scope.row.n_Sort }}</span>
                                                </template>
                                            </el-table-column>
                                        </el-table-column>

                                        <el-table-column min-width="200" :show-overflow-tooltip="true" prop="v_Topic" label="题目" align="center">
                                            <el-table-column :show-overflow-tooltip="true" min-width="200" align="center">
                                                <template #header>
                                                    <SearchModel typeId="i_Topic" typeVal="input" @searchHandel="searchHandel" :basicsInfo="basicsInfo" />
                                                </template>
                                                <template #default="scope">
                                                    <span>{{ scope.row.v_Topic }}</span>
                                                </template>
                                            </el-table-column>
                                        </el-table-column>

                                        <el-table-column min-width="180" :show-overflow-tooltip="true" prop="createdTime" label="创建时间"  align="center" sortable>
                                            <template #default="scope">
                                                <span v-if="scope.row.createdTime">{{ scope.row.createdTime }}</span>
                                                <span v-else>-</span>
                                            </template>
                                        </el-table-column>

                                        <el-table-column min-width="180" :show-overflow-tooltip="true" prop="updatedTime" label="更新时间"  align="center" sortable>
                                            <template #default="scope">
                                                <span v-if="scope.row.updatedTime">{{ scope.row.updatedTime }}</span>
                                                <span v-else>-</span>
                                            </template>
                                        </el-table-column>

                                        <el-table-column min-width="180" label="操作" align="center" fixed="right">
                                            <el-table-column :show-overflow-tooltip="true" min-width="180" align="center">
                                                <template #header>
                                                    <el-button class="icon-e" @click='searchClick' icon="ele-Search" size="small" type="primary" text> 查询 </el-button>
                                                    <el-button class="icon-e clear-bg" style="background-color: transparent !important;" size="small" @click="resetClick" icon="ele-Refresh" text> 重置 </el-button>
                                                </template>
                                                <template #default="scope">
                                                    <div class="operate-s">
                                                        <el-button @click="detailHandle(scope.row.id)" class="icon-e" icon="ele-View" size="small" text type="success">详情</el-button>
                                                        <el-button v-if="$hasPer('QuestionBank:edit')" @click="nodeClick(scope.row,'edit')" class="icon-e" icon="ele-Edit" size="small" text type="primary">编辑</el-button>
                                                        <el-button v-if="$hasPer('QuestionBank:del')" @click="deleteHandle(scope.row.id, getData)" class="icon-e" icon="ele-Delete" size="small" text type="danger">删除</el-button>
                                                    </div>
                                                </template>
                                            </el-table-column>
                                        </el-table-column>
                                    </el-table>
                                </div>
                            </div>
                            <div style="height: 30px;margin-top: 20px;" class="hr-flex-start">
								<el-pagination
									v-model:currentPage="pageNo"
									v-model:page-size="pageSize"
									:total="totalRows"
									:page-sizes="[10, 20, 50, 100]"
									small
									background
									@size-change="handleSizeChange"
									@current-change="handleCurrentChange"
									layout="total, sizes, prev, pager, next, jumper"
									class="w-h-100"
								/>
							</div>
                        </div>
                    </el-card>
                </div>
            </div>
        </div>
        <AddEditQuestionBank
            :repairInfo="repairInfo"
            :isUseDialog="isUseDialog"
            @updateData="getData"
            @cancelUseClick="cancelUseClick"
            @controlUseClick="controlUseClick"
        />
        <MassUpload
            :isBase="true"
            uploadType="tk"
            :neddUrl="needUrl"
            :isUseDialog="massDialog"
            @updateData="getData"
            @cancelMassClick="cancelMassClick"
            @controlMassClick="controlMassClick"
        />
        <!-- 详情 -->
        <DetailModel
            :detailInfo="detailInfo"
            :MdetailDialog="MdetailDialog"
            labelWidth="140px"
            @cancelDetailClick="cancelDetailClick"
        />
    </div>
</template>
<script lang="ts">
import { defineComponent, ref, Ref, onMounted , reactive , toRaw } from 'vue';
import getTableData from '/@/utils/getTableData';
import { 
    OmsEduExaminationDBPage , 
    EduTrainingPlanList , 
    OmsEduExaminationDBDelete , 
    OmsEduExaminationDBBathAddByExcel ,
    OmsEduExaminationDBDetail,
} from '/@/api/centerControl/sms';
import AddEditQuestionBank from '../component/sms/add-edit-QuestionBank.vue';
import { ElMessageBox , ElMessage } from 'element-plus';
import MassUpload from '../component/sms/mass-upload.vue';
import SearchModel from '../component/search-model.vue';
import DetailModel from '../component/detail-model.vue';
import { exportToExcel } from '/@/utils/exportToExcel';

export default defineComponent( {
    name: 'QuestionBank',
    components: {
        AddEditQuestionBank,
        MassUpload,
        SearchModel,
        DetailModel,
    },
    setup(props){
        const isUseDialog = ref(); // 新增/编辑弹出框隐藏/显示
        const repairInfo = ref(); // 传递子组件数据
        const massDialog = ref(false);
        const baseUrl = import.meta.env.VITE_API_URL;
        let planDefaultVal: number = 0;

        /*** nodeClick 新增/编辑点击事件 */
        const nodeClick = (val:string | object , am:string) => {
            val !== '' ? repairInfo.value = JSON.stringify(toRaw(val)) : repairInfo.value = ''
            isUseDialog.value = true
        };

        /*** deleteHandle 删除数据事件 */
        const deleteHandle = async (val: String | Number, updateFun: Function) => {
            ElMessageBox.confirm('请确定删除此条数据？','提示',
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                }
            )
            .then(async() => {
                let param = {id : val}
                try {
                    let res:any = await OmsEduExaminationDBDelete(param);
                    if(res.success){
                        updateFun()
                    }
                } catch (err) { return }
            })
            .catch(() => {
                ElMessage({
                    type: 'info',
                    message: '已取消',
                })
            })
        };

        /*** cancelUseClick 取消事件 */
        const cancelUseClick = () => {
            isUseDialog.value = false
        };

        /*** 提交事件 */
        const controlUseClick = (id: number) => {
            isUseDialog.value = false;
            planDefaultVal = id;
            searchObj.l_TrainingPlanId = id;
            initInfoFun();
        };

        /*** onSuccess 文件上传成功时的钩子函数 */
        const onSuccess = (item:any) => {
            console.log(item,'item')
        };
        
        /*** 批量上传取消事件 */
        const cancelMassClick = () => {
            massDialog.value = false;
        }

        /*** 批量上传提交事件 */
        const controlMassClick = () => {
            massDialog.value = false;
        }

        /*** 上传/下载点击事件 */
        const funClick = (num: number) => {
            if(num === 0) {massDialog.value = true;}
            if(num === 1){
                // window.open('http://xxxx','_blank') // 打开新页面
                window.location.href = baseUrl + '/Upload/SMS/ExcelTempFiles/培训教育-题库导入模板.xlsx'; // 当前页面中打开
            }
        }

        /*** ================================= 详情类数据操作 =================================  */
        const MdetailDialog = ref(false);
        const detailInfo = ref();
        /*** 获取详情接口数据 */
        const getDetailFun = async (id: number) => {
            let res: any = await OmsEduExaminationDBDetail({id: id});
            if(res.success){
                let setArr: any = [];
                let tableArr: any = [];
                let detailObj: any = {};
                detailObj['培训计划名称'] = res.data.v_TrainingPlanName;
                detailObj['考题类型名称'] = res.data.v_TypeName;
                detailObj['单题分数'] = res.data.n_Score;
                detailObj['排序号'] = res.data.n_Sort;
                detailObj['题目'] = res.data.v_Topic;
                res.data.options.map((item: any) => {
                    let itemObj: any = {};
                    itemObj['选项'] = item.v_Option;
                    itemObj['选项内容'] = item.v_Content;
                    itemObj['是否为正确答案'] = item.isTrue ? '是' : '否';
                    tableArr.push(itemObj);
                })
                setArr = [{
                    formTitle: '基础信息',
                    type: 'form',
                    info: detailObj,
                },{
                    tableTitle: '选项明细',
                    type: 'table',
                    listData: tableArr,
                    minWidth: 160,
                }];
                detailInfo.value = setArr;
                MdetailDialog.value = true;
            }
        }
        /*** 详情 */
        const detailHandle = (id: number) => {
            getDetailFun(id);
        }
        /*** 详情关闭事件 */
        const cancelDetailClick = () => {
            MdetailDialog.value = false;
        }
        /*** ================================= 详情类数据操作 =================================  */
        
        /*** ================================= 查询类数据操作 =================================  */
        let searchObj:any = reactive({});
        const basicsInfo: any = ref([]);
        const searInfo: any = ref();

        /*** 获取需要查询的数据 */
        const searchHandel = (val: any) => {
            searInfo.value = val;
        }

        /*** searchClick 查询按钮 */
        const searchClick = () => {
            let newObj = Object.keys(searInfo.value);
            if(newObj.length !== 0){
                newObj.map((i:any) => {
                    searchObj[i] = searInfo.value[i];
                })
            }
        };

        /*** resetClick 重置按钮 */
        const resetClick = () => {
            searInfo.value = {};
            let newObj = Object.keys(searchObj);
            if(newObj.length !== 0){
                newObj.map((i:any) => {
                    searchObj[i] = ''
                })
            }
            searchObj.l_TrainingPlanId = planDefaultVal;
            initInfoFun();
        };
        
        let planArr: any = [];
        /*** getPlanList 获取培训计划列表 */
        const getPlanList = async() => {
            let param = {}
            let res:any = await EduTrainingPlanList(param);
            if(res.success && res.data.length !==0){
                res.data.map((item: any) => {
                    item.label = item.v_CourseName;
                    item.value = item.id;
                });
                planDefaultVal = res.data[0].value;
                planArr = res.data;
                searchObj.l_TrainingPlanId = planDefaultVal;
            }
        };
        
        /*** 初始化数据 */
        const initInfoFun = () => {
            basicsInfo.value = [{
                    typeId: 's_Plan', // 类型(不能为空，且唯一，与组件中typeId值对应) --- 必填
                    typeNam: '', // 输入类型(number,text等) --- 选填
                    searchVal: 'l_TrainingPlanId', // 查询字段 --- 必填
                    defaultVal: planDefaultVal, // 字段默认值 --- 选填
                    placeholder: '培训计划', // placeholder数据 --- 必填
                    defaultProp: planArr, // 下拉框中使用，除下拉框外其它情况为空 --- 选填
                    eventType: 'change', // 事件类型(如burl/change等) --- 选填
                    defaultEvent: 'planChange', // 事件名称 --- 选填
                },{
                    typeId: 's_Type', // 类型(不能为空，且唯一，与组件中typeId值对应) --- 必填
                    typeNam: '', // 输入类型(number,text等) --- 选填
                    searchVal: 'n_Type', // 查询字段 --- 必填
                    defaultVal: '', // 字段默认值 --- 选填
                    placeholder: '考题类型', // placeholder数据
                    defaultProp: [
                        {label: '单选',value: 0},
                        {label: '多选',value: 1},
                        {label: '判断',value: 2},
                    ], // 下拉框中使用，除下拉框外其它情况为空 --- 选填
                    eventType: 'change', // 事件类型（如burl/change等） --- 选填
                    defaultEvent: 'typeChange', // 事件名称 --- 选填
                },{
                    typeId: 'i_Score', // 类型(不能为空，且唯一，与组件中typeId值对应) --- 必填
                    typeNam: 'number', // 输入类型(number,text等) --- 选填
                    searchVal: 'n_Score', // 查询字段 --- 必填
                    defaultVal: '', // 字段默认值 --- 选填
                    placeholder: '单题分数', // placeholder数据
                    defaultProp: '', // 下拉框中使用，除下拉框外其它情况为空 --- 选填
                    eventType: 'burl', // 事件类型（如burl/change等） --- 选填
                    defaultEvent: 'scoreEvent', // 事件名称 --- 选填
                },{
                    typeId: 'i_Sort', // 类型(不能为空，且唯一，与组件中typeId值对应) --- 必填
                    typeNam: 'number', // 输入类型(number,text等) --- 选填
                    searchVal: 'n_Sort', // 查询字段 --- 必填
                    defaultVal: '', // 字段默认值 --- 选填
                    placeholder: '排序号', // placeholder数据
                    defaultProp: '', // 下拉框中使用，除下拉框外其它情况为空 --- 选填
                    eventType: 'burl', // 事件类型（如burl/change等） --- 选填
                    defaultEvent: 'sortEvent', // 事件名称 --- 选填
                },{
                    typeId: 'i_Topic', // 类型(不能为空，且唯一，与组件中typeId值对应) --- 必填
                    typeNam: '', // 输入类型(number,text等) --- 选填
                    searchVal: 'v_Topic', // 查询字段 --- 必填
                    defaultVal: '', // 字段默认值 --- 选填
                    placeholder: '题目', // placeholder数据
                    defaultProp: '', // 下拉框中使用，除下拉框外其它情况为空 --- 选填
                    eventType: 'burl', // 事件类型（如burl/change等） --- 选填
                    defaultEvent: 'topicEvent', // 事件名称 --- 选填
                },
            ]
        }

        onMounted(async() => {
            await getPlanList();
            initInfoFun();
        });
        /*** ================================= 查询类数据操作 =================================  */

        /*** ================================= 导出数据函数操作 ================================= */
        const excelRef: any = ref(null);
        const handleExport = () => {
            if(excelRef.value){
                if(excelRef.value.data.length !== 0){
                    let tableExcel: any = [];
                    let tableArr = excelRef.value.data;
                    tableArr.map((item: any) => {
                        let tableObj: any = {};
                        tableObj['培训计划名称'] = item.v_TrainingPlanName ? item.v_TrainingPlanName : '-';
                        tableObj['考题类型名称'] = item.v_TypeName ? item.v_TypeName : '-';
                        tableObj['单题分数'] = item.n_Score ? item.n_Score : '-';
                        tableObj['排序号'] = item.n_Sort ? item.n_Sort : '-';
                        tableObj['题目'] = item.v_Topic ? item.v_Topic : '-';
                        tableExcel.push(tableObj);
                    });
                    exportToExcel(tableExcel,'考核题库.xlsx');
                }else{
                    ElMessage({
                        type: 'error',
                        message: '暂无数据导出',
                    })
                }
            }
        }
        /*** ================================= 导出数据函数操作 ================================= */

        return {
            ...getTableData(OmsEduExaminationDBPage,{},searchObj),
            isUseDialog,
            cancelUseClick,
            controlUseClick,
            nodeClick,
            repairInfo,
            deleteHandle,
            resetClick,
            searchClick,
            onSuccess,

            funClick,
            needUrl: OmsEduExaminationDBBathAddByExcel,
            massDialog,
            cancelMassClick,
            controlMassClick,

            // 导出Excel
            excelRef,
            handleExport,

            // 详情
            MdetailDialog,
            detailHandle,
            detailInfo,
            cancelDetailClick,

            // 查询事件
            basicsInfo,
            searchHandel,
        }
    },
} )
</script>
<style lang="scss"> @import '../style/public.scss'; </style>
<style scoped lang="scss">
    #friend-merchant-manage {
        .box-f{
            :deep(.el-form-item__label){
                padding: 0;
            }
        }
        :deep(.el-card__body) {
            height: 100%;
        }
        :deep(.el-card){
            border: none !important;
        }
        .upload-demo{
            margin-left: 12px;
            margin-top: 2px;
        }
        ul {

            list-style: none;

            li {
                cursor: pointer;

                &:hover {
                    color: red;
                }
            }
        }
        .icon-e{
            :deep(.el-icon){
                margin-right: 0px!important;
            }
        }
    }
.clear-bg{
    background-color: transparent !important;
}
</style>